#pragma once 
#include<unordered_map>
#include<iostream>
#include<fstream>
#include<unistd.h>
#include"Log.hpp"

using namespace log_ddsm;

const std::string spare = ": ";

class Dict
{
private:
    void Load(const std::string& path)
    {
        //打开文件
        std::ifstream in(path);
        if(!in.is_open())
        {
            LOG(FATAL,"open file fail!\n");
            exit(1);
        }

        std::string line;
        while(std::getline(in,line))
        {
            //跳过空行
            if(line.empty()) continue;

            auto pos = line.find(spare.c_str());
            //找不到分隔符
            if(pos == std::string::npos) continue;

            //cat: 猫
            //解析对应的key val
            std::string key = line.substr(0,pos);
            std::string val = line.substr(pos + spare.size());
            //插入
            _dict.insert(std::make_pair(key,val));

            LOG(DEBUG,"load %s success!\n",line.c_str());
        }

        in.close();//关闭文件
    }
public:
    Dict(const std::string& dictpath)
        :_path(dictpath)
        ,_dict()
    {
        //加载字典的内容
        Load(dictpath);
    }

    std::string Translate(const std::string& word)
    {
        if(word.empty())//翻译的词为空
            return "None";
        auto iter = _dict.find(word);
        if(iter == _dict.end())//找不到翻译的词
            return "None";
        return iter->second;
    }

    ~Dict()
    {}
private:
    //字典，本质上是一个哈希表
    std::unordered_map<std::string,std::string> _dict;
    //字典文件所在的目录
    std::string _path;
};

